/*
 * Exploder
 * 
 * Tero Pyylampi (218437), Jussi Tuurinkoski (211594)
 *
 * Interface for saving & loading user data
 * which includes everything related to game
 */

#include "UserData.h"

#include <string>
#include <sstream>

using namespace cocos2d;

// default constructor, loads settings
UserData::UserData( unsigned int playerNro ) : mPlayerNro( playerNro ) {
	// create data holder
	mGameData = new GameData();
	// read data
	loadAllSettingsAndData();
}

// default desturctor, saves settings
UserData::~UserData() {
	saveAllSettingsAndData();
	delete mGameData;
}

// get saved game data
GameData *UserData::getGameData() {
	return mGameData;
}

// explicitely save settings
void UserData::saveAllSettingsAndData() {
	// TODO: tag should depend on player number
	string tag = "p0";

	// save current money
	CCUserDefault::sharedUserDefault()->setIntegerForKey( string( tag + "-expMoney" ).c_str(), mGameData->currentMoney );

	// save levels reached
	std::string lvl = createLevelString( mGameData->starsCollected );
	CCUserDefault::sharedUserDefault()->setStringForKey( string( tag + "-expLevels" ).c_str(), lvl );

	// make changes persistent
	CCUserDefault::sharedUserDefault()->flush();
}

// loads settings and data
void UserData::loadAllSettingsAndData() {
	// TODO: tag should depend on player number
	string tag = "p0";

	// load game data
	mGameData->currentMoney = CCUserDefault::sharedUserDefault()->getIntegerForKey( string( tag + "-expMoney" ).c_str(), 0 );

	// load stars collected
	std::string t = CCUserDefault::sharedUserDefault()->getStringForKey( string( tag + "-expLevels" ).c_str(), "0 0 0 0 0 0 0 0 0 0" );
	mGameData->starsCollected = parseLevelString( t );
}

// creates the string to be parsed for levels
std::string UserData::createLevelString( unsigned int *levels ) {
	std::string levelString;
	// loop through items
	for( unsigned int j = 0; j < 10; ++j ) {
		char tmp[ 3 ];
		sprintf( tmp, "%d ", levels[ j ] );
		levelString.append( tmp );
	}
	return levelString;
}

// returns the stars for levels
unsigned int *UserData::parseLevelString( std::string s ) {
	// parse string
	unsigned int *tmp = new unsigned int[ 10 ];
	const char *str = s.c_str();
	sscanf( str, "%d %d %d %d %d %d %d %d %d %d", 
		&tmp[ 0 ], &tmp[ 1 ], &tmp[ 2 ], &tmp[ 3 ], &tmp[ 4 ], 
		&tmp[ 5 ], &tmp[ 6 ], &tmp[ 7 ], &tmp[ 8 ], &tmp[ 9 ] );
	
	return tmp;
}
